#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/7/28 09:46
# @Author  : youfeng
from ext.redis_handler import RedisHandler

try:
    import cPickle as pickle
except ImportError:
    import pickle


class SessionManage(object):
    # 秒为单位
    MAX_AGE = 20

    # session key
    SESSION_KEY = 'gsxt_session'

    def __init__(self, cache_conf, log=None):
        self.log = log
        self.redis_handler = RedisHandler(cache_conf['host'],
                                          cache_conf['port'],
                                          cache_conf['password'],
                                          cache_conf['db'],
                                          cache_conf['max_connections'])

    def __get_session_from_redis(self):
        session_str = self.redis_handler.get("gsxt_session")
        if session_str is None:
            return None

        try:
            session = pickle.loads(session_str)
            return session
        except Exception as e:
            self.log.error("session 反序列化异常:")
            self.log.exception(e)

        return None

    def get_session(self):
        # 先从redis中拿redis 如果没有，则重新生成
        session = self.__get_session_from_redis()
        if session is not None:
            # self.log.info("从 redis中获取session 成功...")
            return session

        # self.log.warn("从redis中获取session失败,需要重新生成...")
        return None

    def save_session(self, session):
        try:
            session_str = pickle.dumps(session)
            self.redis_handler.set(self.SESSION_KEY, session_str, ex=self.MAX_AGE)
            self.log.info("session 保存成功")
        except Exception as e:
            self.log.error("存储session 到redis异常:")
            self.log.exception(e)
